package com.firexxx.vp.adapter.scheduled;

import com.firexxx.common.utils.UUIDUtil;
import com.firexxx.vp.application.dto.StbDto;
import com.firexxx.vp.application.thread.StbRegisterThread;
import com.firexxx.vp.domain.stb.StbEntity;
import com.firexxx.vp.domain.stb.StbRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/02/15 20:11
 */
@Component
@Slf4j
public class RegisterScheduledManager {

    @Autowired
    private StbRepository stbRepository;

    @Autowired
    private StbRegisterThread stbRegisterThread;

    @Scheduled(cron = "${register.cron:0 0 0/1 * * ?}")
    public void registerScheduled() {
        if (!stbRegisterThread.getQueue().isEmpty()) {
            log.info("现存任务还未执行完,本次任务取消");

            return;
        }

        List<StbEntity> stbEntityList = stbRepository.findAll();
        Optional.of(stbEntityList).orElse(Collections.emptyList()).stream().forEach(stbEntity -> {
            StbDto stbDto = new StbDto(UUIDUtil.strings(), stbEntity.getStbKey().getChannelId(),
                    stbEntity.getStbKey().getStbId(), stbEntity.getStbKey().getMac());

            stbRegisterThread.getQueue().add(stbDto);
        });
    }

}